import os
import time

from flask import Blueprint, request, jsonify, make_response, json
from flask_restful import Api,Resource
from flask import current_app as app
from uitils.comm import get_data
from db import db1
from uitils.acl import aci
from uitils.jwton import jwte
from uitils.redison import red


qianname = Blueprint('qianname',__name__)


@qianname.route('/workflow')
def workflow():
    sql = "select * from workflow"
    res = db1.findall(sql)
    return jsonify({'code':200,'list':res})


@qianname.route('/getcoursedata')
def getcoursedata():
    # 先从redis中取数据
    key = 'coursedata'
    value = red.set_get_str(key)
    if value:
        list = eval(value)

    else:
        # 如果redis中不存在,去数据库中查询
        sql = "select * from data_source"
        res = db1.findall(sql)
        list = []
        if res:
            for i in res:
                dict = {'id':i['id'],'name':i['name']}
                sql1 = "select id,name,type from %s"%(i['tablename'])
                res1 = db1.findall(sql1)
                dict['mes'] = res1
                list.append(dict)

        # 存入redis
        red.set_str(key,json.dumps(list))
    return jsonify({'code':200,'list':list})



@qianname.route('/addcoursedata',methods=['POST'])
def addcoursedata():
    id = request.args.get('id')
    data = get_data()
    sql = "update workflow set params='{}' where id={}".format(data['data'],int(id))
    print(sql)
    db1.update(sql)
    return jsonify({'code':200,'msg':'添加成功'})


@qianname.route('/getrespid',methods=['GET','POST'])
def getrespid():
    if request.method == 'POST':
        data = get_data()
        sql = "insert into resources(name,url,status,pid) values('{}','{}',{},{})".format(data['name'],data['url'],int(data['status']),int(data['pid']))
        db1.update(sql)
        return jsonify({'code': 200, 'msg': '添加成功'})
    else:
        sql = "select * from resources where pid=0"
        res = db1.findall(sql)
        return jsonify({'code':200,'list':res})



@qianname.route('/getparams')
def getparams():
    id = request.args.get('id')
    sql = "select * from workflow where id={}".format(int(id))
    res = db1.find(sql)
    return jsonify({'code':200,'list':res})


@qianname.route('/imgfile',methods=['POST'])
def imgfile():
    file = request.files['file']
    file.save(os.path.join('./static/iimg/' + file.filename))
    img = 'http://localhost:5000/static/iimg/' + file.filename
    return jsonify({'code': 200, 'list': img})

@qianname.route('/submit_task',methods=['POST'])
def submit_task():
    data =get_data()
    print(data)
    sql = "select * from workflow where id={}".format(int(data['wid']))
    res = db1.find(sql)
    tt = data['姓名']+res['name']
    params = str(data)
    sql1 = "insert into task(id,title,params,status,review) values(0.'{}','{}',1,'{}')".format(tt,params,data['ids'])
    print(sql1)
    db1.update(sql1)
    return jsonify({'code':200,'msg':'添加成功'})